package com.allkapps.bbmopenchat;

import com.allkapps.bbmopenchat.BBMOpenChatMessagingServiceListener;
import com.allkapps.bbmopenchat.BaseScreen;

import net.rim.blackberry.api.bbm.platform.io.BBMPlatformConnection;
import net.rim.blackberry.api.bbm.platform.io.BBMPlatformSession;
import net.rim.blackberry.api.bbm.platform.profile.BBMPlatformContactList;
import net.rim.blackberry.api.bbm.platform.profile.ContactListProvider;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;

/**
 * A class extending the MainScreen class, which provides default standard
 * behavior for BlackBerry GUI applications.
 */
public final class SampleBBMScreen extends BaseScreen
{
	private BBMPlatformSession sess = null;
	private ButtonField create = null;
	private ButtonField invite = null;
	
	public SampleBBMScreen()
    {        
        // Set the displayed title of the screen       
        setTitle("BBMOpendChat");
        create = new ButtonField("Create Session", ButtonField.CONSUME_CLICK);
        create.setChangeListener(new FieldChangeListener() {
			
			public void fieldChanged(Field field, int context) {
				BBMPlatformConnection conn = BBMBridge.getInstance().createSession();
				BBMBridge.getInstance().addConnection(conn);
				((BBMOpenChatConnectionListener)conn.getListener()).setScreen(SampleBBMScreen.this);
				invite.setEnabled(true);
				setEnabled(false);
			}
		});
        
        invite = new ButtonField("Invite Contact", ButtonField.CONSUME_CLICK);
        invite.setChangeListener(new FieldChangeListener() {
			
			public void fieldChanged(Field field, int context) {
				sess.sendInvitation("Come join my session", "cookie", 5*60*1000L);
			}
		});
    }
	
	public boolean onClose()
	{
		return super.onClose();
	}
	
	public boolean onSavePrompt()
	{
		return true;
	}
	
	public void error(String error) {
		System.out.println(error);
	}

	public void updateScreen(int type) {
		switch(type){
			case BaseScreen.INVITE_ACCEPTED:
				synchronized(UiApplication.getEventLock()){
					Dialog.inform("Invite Accepted");
				}
				break;
			default:
				break;
		}
	}
	
	public void updateScreen(int type, Object obj){
		switch(type){
		//When you join a session.
		case BaseScreen.SESSION_CREATED:
			BBMPlatformSession sess = (BBMPlatformSession)obj;
			this.sess = sess;
			((BBMOpenChatConnectionListener)this.sess.getListener()).setScreen(this);
			synchronized(UiApplication.getEventLock()) {
				Dialog.inform("Session was created, you are connected to someone else.");
			}
			break;
		default:
			break;
		}
	}
}
